<template>
  <div class="custom-form">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px"
        :key="showFormKey" v-if="showForm">
        <el-col :span="7" v-show="hasFormPermission('company_id')">
          <el-form-item :label="$t('企业名称')" prop="company_id">
            <el-input v-model="formData['company_id']" placeholder="请输入企业名称"
              :disabled="hasDisabledPermission('company_id',false)"
              :readonly="!hasEditPermission('company_id',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_year')">
          <el-form-item :label="$t('年度')" prop="cl_year">
            <el-input v-model="formData['cl_year']" placeholder="请输入年度"
              :disabled="hasDisabledPermission('cl_year',false)"
              :readonly="!hasEditPermission('cl_year',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_month')">
          <el-form-item :label="$t('月度')" prop="cl_month">
            <el-input v-model="formData['cl_month']" placeholder="请输入月度"
              :disabled="hasDisabledPermission('cl_month',false)"
              :readonly="!hasEditPermission('cl_month',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('purchase_order_count')">
          <el-form-item :label="$t('采购订单条数')" prop="purchase_order_count">
            <el-input v-model.number="formData['purchase_order_count']" type="number" placeholder="请输入采购订单条数"
              :disabled="hasDisabledPermission('purchase_order_count',false)"
              :readonly="!hasEditPermission('purchase_order_count',false)" clearable
              :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('order_number')">
          <el-form-item :label="$t('新增订单数量')" prop="order_number">
            <el-input v-model.number="formData['order_number']" type="number" placeholder="请输入新增订单数量"
              :disabled="hasDisabledPermission('order_number',false)"
              :readonly="!hasEditPermission('order_number',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('production_number')">
          <el-form-item :label="$t('生产数量')" prop="production_number">
            <el-input v-model.number="formData['production_number']" type="number" placeholder="请输入生产数量"
              :disabled="hasDisabledPermission('production_number',false)"
              :readonly="!hasEditPermission('production_number',false)" clearable
              :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('lead_time')">
          <el-form-item :label="$t('交付周期')" prop="lead_time">
            <el-input v-model.number="formData['lead_time']" type="number" placeholder="请输入交付周期"
              :disabled="hasDisabledPermission('lead_time',false)"
              :readonly="!hasEditPermission('lead_time',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('black_order')">
          <el-form-item :label="$t('黑单占比')" prop="black_order">
            <el-input v-model.number="formData['black_order']" type="number" placeholder="请输入黑单占比"
              :disabled="hasDisabledPermission('black_order',false)"
              :readonly="!hasEditPermission('black_order',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('w_floor_eff')">
          <el-form-item :label="$t('仓库坪效')" prop="w_floor_eff">
            <el-input v-model.number="formData['w_floor_eff']" type="number" placeholder="请输入仓库坪效"
              :disabled="hasDisabledPermission('w_floor_eff',false)"
              :readonly="!hasEditPermission('w_floor_eff',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_itr')">
          <el-form-item :label="$t('库存周转率(ITO)%')" prop="cl_itr">
            <el-input v-model.number="formData['cl_itr']" type="number" placeholder="请输入库存周转率(ITO)%"
              :disabled="hasDisabledPermission('cl_itr',false)"
              :readonly="!hasEditPermission('cl_itr',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_ppcr')">
          <el-form-item :label="$t('采购计划完成率')" prop="cl_ppcr">
            <el-input v-model.number="formData['cl_ppcr']" type="number" placeholder="请输入采购计划完成率"
              :disabled="hasDisabledPermission('cl_ppcr',false)"
              :readonly="!hasEditPermission('cl_ppcr',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('po_cycle')">
          <el-form-item :label="$t('原材料采购周期')" prop="po_cycle">
            <el-input v-model.number="formData['po_cycle']" type="number" placeholder="请输入原材料采购周期"
              :disabled="hasDisabledPermission('po_cycle',false)"
              :readonly="!hasEditPermission('po_cycle',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_opc')">
          <el-form-item :label="$t('人均产值')" prop="cl_opc">
            <el-input v-model.number="formData['cl_opc']" type="number" placeholder="请输入人均产值"
              :disabled="hasDisabledPermission('cl_opc',false)"
              :readonly="!hasEditPermission('cl_opc',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('m_floor_eff')">
          <el-form-item :label="$t('生产坪效')" prop="m_floor_eff">
            <el-input v-model.number="formData['m_floor_eff']" type="number" placeholder="请输入生产坪效"
              :disabled="hasDisabledPermission('m_floor_eff',false)"
              :readonly="!hasEditPermission('m_floor_eff',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_pcr')">
          <el-form-item :label="$t('计划完成率')" prop="cl_pcr">
            <el-input v-model.number="formData['cl_pcr']" type="number" placeholder="请输入计划完成率"
              :disabled="hasDisabledPermission('cl_pcr',false)"
              :readonly="!hasEditPermission('cl_pcr',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('mf_cycle')">
          <el-form-item :label="$t('制造周期')" prop="mf_cycle">
            <el-input v-model.number="formData['mf_cycle']" type="number" placeholder="请输入制造周期"
              :disabled="hasDisabledPermission('mf_cycle',false)"
              :readonly="!hasEditPermission('mf_cycle',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('poq_rate')">
          <el-form-item :label="$t('来料合格率')" prop="poq_rate">
            <el-input v-model.number="formData['poq_rate']" type="number" placeholder="请输入来料合格率"
              :disabled="hasDisabledPermission('poq_rate',false)"
              :readonly="!hasEditPermission('poq_rate',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('qp_rate')">
          <el-form-item :label="$t('品质直通率')" prop="qp_rate">
            <el-input v-model.number="formData['qp_rate']" type="number" placeholder="请输入品质直通率"
              :disabled="hasDisabledPermission('qp_rate',false)"
              :readonly="!hasEditPermission('qp_rate',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_asr')">
          <el-form-item :label="$t('应收销售比')" prop="cl_asr">
            <el-input v-model.number="formData['cl_asr']" type="number" placeholder="请输入应收销售比"
              :disabled="hasDisabledPermission('cl_asr',false)"
              :readonly="!hasEditPermission('cl_asr',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_otd')">
          <el-form-item :label="$t('准交率(OTD)')" prop="cl_otd">
            <el-input v-model.number="formData['cl_otd']" type="number" placeholder="请输入准交率(OTD)"
              :disabled="hasDisabledPermission('cl_otd',false)"
              :readonly="!hasEditPermission('cl_otd',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_mon_sgr')">
          <el-form-item :label="$t('环比销售增长率')" prop="cl_mon_sgr">
            <el-input v-model.number="formData['cl_mon_sgr']" type="number" placeholder="请输入环比销售增长率"
              :disabled="hasDisabledPermission('cl_mon_sgr',false)"
              :readonly="!hasEditPermission('cl_mon_sgr',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_yoy_sgr')">
          <el-form-item :label="$t('同比销售增长率')" prop="cl_yoy_sgr">
            <el-input v-model.number="formData['cl_yoy_sgr']" type="number" placeholder="请输入同比销售增长率"
              :disabled="hasDisabledPermission('cl_yoy_sgr',false)"
              :readonly="!hasEditPermission('cl_yoy_sgr',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_gpm')">
          <el-form-item :label="$t('平均毛利率')" prop="cl_gpm">
            <el-input v-model.number="formData['cl_gpm']" type="number" placeholder="请输入平均毛利率"
              :disabled="hasDisabledPermission('cl_gpm',false)"
              :readonly="!hasEditPermission('cl_gpm',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_price')">
          <el-form-item :label="$t('产品平均单价')" prop="cl_price">
            <el-input v-model.number="formData['cl_price']" type="number" placeholder="请输入产品平均单价"
              :disabled="hasDisabledPermission('cl_price',false)"
              :readonly="!hasEditPermission('cl_price',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('cl_ftd')">
          <el-form-item :label="$t('外贸依赖度')" prop="cl_ftd">
            <el-input v-model.number="formData['cl_ftd']" type="number" placeholder="请输入外贸依赖度"
              :disabled="hasDisabledPermission('cl_ftd',false)"
              :readonly="!hasEditPermission('cl_ftd',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('create_date')">
          <el-form-item :label="$t('时间')" prop="create_date">
            <el-date-picker :disabled="hasDisabledPermission('create_date',true)"
              :readonly="!hasEditPermission('create_date',true)" v-model="formData['create_date']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('field128945a')">
          <el-form-item :label="$t('最后跟新时间')" prop="field128945a">
            <el-date-picker :disabled="hasDisabledPermission('field128945a',false)"
              :readonly="!hasEditPermission('field128945a',false)" v-model="formData['field128945a']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择最后跟新时间"
              clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('creater')">
          <el-form-item :label="$t('创建人')" prop="creater">
            <el-input v-model="formData['creater']" placeholder="请输入创建人"
              :disabled="hasDisabledPermission('creater',true)"
              :readonly="!hasEditPermission('creater',true)" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7" v-show="hasFormPermission('updater')">
          <el-form-item :label="$t('更新人')" prop="updater">
            <el-input v-model="formData['updater']" placeholder="请输入更新人"
              :disabled="hasDisabledPermission('updater',true)"
              :readonly="!hasEditPermission('updater',true)" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="!isWorkflowForm">
          <el-form-item size="large" v-if="isEdit" class="form-button-center">
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              {{submitLoading?$t('workFlow.WFMenu.hintSubmit'):$t('submit')}}</el-button>
            <el-button @click="cancelForm">{{$t('cancelText')}}</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>

        import workflowFormAuthorize from "@/mixins/workflowFormAuthorize";
        import authorizeMixin from "@/mixins/authorize";
        import nodeMsgMixin from "@/mixins/nodeMsg";
        import { baseUrl } from "@/config/env";
        import request from "@/router/axios";
        import {fieldsConfig,formFieldsMap,getHideComponents} from './monthkpiConfig';
        import { formValidateNotice } from '@/util/util';		
        import store from "@/store";
        import hideComponentsMixin from "@/mixins/hideComponents"; // 隐藏组件
        export default {
          mixins: [authorizeMixin,workflowFormAuthorize,nodeMsgMixin,hideComponentsMixin],
       
  components: {},
  props: ['keyValue', 'isEdit', 'disabled'],
  data() {
    return {
      userInfo: {},
      submitLoading: false,
      showForm: true,
      showFormKey: 1,
      reRenderSubform: false,
      operationVal: 'add',
      isAdd: true,
      addressUrl:'monthkpi',
      autoCompleteConfEventData: [],
      mainTableName: 'dw_month_kpi_data',
      formConfig: {},
      formFieldsMap: new Map(),
      hideComponentsMap: new Map(),
      needShowValueTags: ['asso-popup', 'mutiple-popup'],
      formData: {
        'company_id': '',
        'cl_year': '',
        'cl_month': '',
        'purchase_order_count': 0,
        'order_number': 0,
        'production_number': 0,
        'lead_time': 0,
        'black_order': 0,
        'w_floor_eff': 0,
        'cl_itr': 0,
        'cl_ppcr': 0,
        'po_cycle': 0,
        'cl_opc': 0,
        'm_floor_eff': 0,
        'cl_pcr': 0,
        'mf_cycle': 0,
        'poq_rate': 0,
        'qp_rate': 0,
        'cl_asr': 0,
        'cl_otd': 0,
        'cl_mon_sgr': 0,
        'cl_yoy_sgr': 0,
        'cl_gpm': 0,
        'cl_price': 0,
        'cl_ftd': 0,
        'create_date': null,
        'field128945a': null,
        'creater': '',
        'updater': '',
      },
      rules: {
        company_id: [{
          required: true,
          message: '请输入企业名称',
          trigger: 'blur'
        }],
        cl_year: [{
          required: true,
          message: '请输入年度',
          trigger: 'blur'
        }],
        cl_month: [{
          required: true,
          message: '请输入月度',
          trigger: 'blur'
        }],
        purchase_order_count: [{
          required: true,
          message: '请输入采购订单条数',
          trigger: 'blur'
        }],
        order_number: [{
          required: true,
          message: '请输入新增订单数量',
          trigger: 'blur'
        }],
        production_number: [{
          required: true,
          message: '请输入生产数量',
          trigger: 'blur'
        }],
        lead_time: [{
          required: true,
          message: '请输入交付周期',
          trigger: 'blur'
        }],
        black_order: [{
          required: true,
          message: '请输入黑单占比',
          trigger: 'blur'
        }],
        w_floor_eff: [{
          required: true,
          message: '请输入仓库坪效',
          trigger: 'blur'
        }],
        cl_itr: [{
          required: true,
          message: '请输入库存周转率(ITO)%',
          trigger: 'blur'
        }],
        cl_ppcr: [{
          required: true,
          message: '请输入采购计划完成率',
          trigger: 'blur'
        }],
        po_cycle: [{
          required: true,
          message: '请输入原材料采购周期',
          trigger: 'blur'
        }],
        cl_opc: [{
          required: true,
          message: '请输入人均产值',
          trigger: 'blur'
        }],
        m_floor_eff: [{
          required: true,
          message: '请输入生产坪效',
          trigger: 'blur'
        }],
        cl_pcr: [{
          required: true,
          message: '请输入计划完成率',
          trigger: 'blur'
        }],
        mf_cycle: [{
          required: true,
          message: '请输入制造周期',
          trigger: 'blur'
        }],
        poq_rate: [{
          required: true,
          message: '请输入来料合格率',
          trigger: 'blur'
        }],
        qp_rate: [{
          required: true,
          message: '请输入品质直通率',
          trigger: 'blur'
        }],
        cl_asr: [{
          required: true,
          message: '请输入应收销售比',
          trigger: 'blur'
        }],
        cl_otd: [{
          required: true,
          message: '请输入准交率(OTD)',
          trigger: 'blur'
        }],
        cl_mon_sgr: [{
          required: true,
          message: '请输入环比销售增长率',
          trigger: 'blur'
        }],
        cl_yoy_sgr: [{
          required: true,
          message: '请输入同比销售增长率',
          trigger: 'blur'
        }],
        cl_gpm: [{
          required: true,
          message: '请输入平均毛利率',
          trigger: 'blur'
        }],
        cl_price: [{
          required: true,
          message: '请输入产品平均单价',
          trigger: 'blur'
        }],
        cl_ftd: [{
          required: true,
          message: '请输入外贸依赖度',
          trigger: 'blur'
        }],
        create_date: [],
        field128945a: [{
          required: true,
          message: '请选择最后跟新时间',
          trigger: 'change'
        }],
        creater: [],
        updater: [],
      },
    }
  },
  computed: {},
  watch: {
    'formData.purchase_order_count': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.order_number': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.production_number': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.lead_time': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.black_order': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.w_floor_eff': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_itr': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_ppcr': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.po_cycle': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_opc': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.m_floor_eff': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_pcr': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.mf_cycle': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.poq_rate': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.qp_rate': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_asr': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_otd': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_mon_sgr': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_yoy_sgr': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_gpm': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_price': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.cl_ftd': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
  },
  async created() {
    this.formConfig = this.getFormConfig();
    this.formFieldsMap = this.getFormFieldsMap();
    this.userInfo = localStorage.getItem("avue-userInfo") ? JSON.parse(localStorage.getItem(
      "avue-userInfo")).content : {};
  },
  async mounted() {
    this.hideComponentsMap = await this.getHideComponentsMap();
    this.showForm = false;
    await this.insertCreatedEvent();
    //TODO   再这里做数据回填 请求表单数据
   
           if(this.keyValue){
              this.isAdd = false;
          }
           if(!this.isAdd&&this.keyValue){
              this.operationVal = 'edit';
              try {
                let res = await request({
                  url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
                  method: "get",
                });
                  
            this.formData = res.data.data
            
                  await this.handleEdit();
                 this.showFormKey++;
              } catch (error) {
              }
          }

       
    await this.insertMountedEvent();
    this.reRenderSubform = true; //子表单显示
    this.showFormKey++;
    this.processParameterAssignment();
    this.showForm = true;
  },
  methods: {
    getFormData() {
      let key = this.mainTableName + 'Entity';
      let returnParams = {};
      returnParams[key] = this.formData;
      return {
        ...returnParams,
      };
    },
    validateForm() {
      this.$refs['elForm'].validate(valid => {});
    },
    async aysncValidateForm() {
      let validataArry = []
      let formValidateNotice = function formValidateNotice(obj, that, formAuth) {
        for (var o in obj) {
          if (!formAuth[o] && obj[o][0]) {
            that.$message({
              message: obj[o][0].message + ',' + that.$t('noFormAuth'),
              type: 'warning'
            });
            return;
          }
        }
      }
      validataArry.push(new Promise((resolve, reject) => {
        this.$refs['elForm'].validate((valid, object) => {
          if (!this.isWorkflowForm) formValidateNotice(object, this, this.formEnCodeList)
          resolve(valid)
        })
      }))
      let res = await Promise.all(validataArry)
      if (res.includes(false)) {
        return false
      }
      else {
        return true;
      }
    },
    changeTableData() {},
    async submitForm() {
      this.submitLoading = true;
      let valid = await this.aysncValidateForm();
      if (valid == false) {
        this.submitLoading = false;
        return false;
      }
      this.changeTableData();
      //格式化数据
      let newObj = this.getFormData();
      
        //如果没有传入参数就是新增
        if (!this.keyValue) {

          request({
            url: baseUrl + "/"+this.addressUrl,
            method: "post",
            data : newObj
          }).then((res) => {
            this.submitLoading = false;
            this.$notify({
              title: "成功",
              message: "新增成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
        else{

         request({
            url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
            method: "put",
            data : newObj
          }).then((res) => {
            this.submitLoading = false;
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
       
       
      
      
      await this.handleSubmit();
    },
    cancelForm() {
      this.$emit("onChange", true)
    },
    formatTree(data, valueField, lableField, childField, type) {
      let tree = [];
      data.forEach((node, index) => {
        let newNode = {
          value: node[valueField],
          label: node[lableField],
        };
        if (type) {
          newNode.disabled = node[valueField] == undefined ? true : false
        }
        tree.push(newNode);
        if (node[childField] != null && node[childField].length > 0) {
          newNode.children = (this.formatTree(node[childField], valueField, lableField, childField,
          type));
        }
      }, this);
      return tree;
    },
    
          //辅助编辑 预留方法
          async handleEdit() {
            await this.insertEditEvent();
          },
          
    //FORM_EVENT_EDIT
    
        //辅助提交 预留方法
        async handleSubmit() {
          await this.insertSubmitEvent();
        },
        //辅助工作流提交 预留方法
        getHandleSubmitFormEvent() {
            
        },
        //辅助工作流表单事件 判断 表单事件是否已经执行过
        getisExecutedFormEvent() {
            let key = 'index'+this.$store.state.formParser.workflowFormTabIndexKey;
            return this.$store.state.formParser.isExecutedFormEvent[key]?this.$store.state.formParser.isExecutedFormEvent[key]:false;
            
        },
      
    getNumberFixed2(number) {
      let splitNum = ("" + number).replace(/(^0*)/g, "").split(".");
      let num = splitNum[0] == "" ? '0' : splitNum[0];
      if (splitNum.length > 1) {
        num += '.';
        let roundNum = 2; //保留两位小数
        for (let i = 0; i < roundNum; i++) {
          num += splitNum[1][i];
        }
      }
      return parseFloat(num);
    },
    changeFormConfigDefaultValue() {
      let valueForFormIdMap = new Map();
      this.formConfig.fields.forEach((ele) => {
        if (ele.__config__.componentName == "table") {
          ele.__config__.children.forEach((element) => {
            valueForFormIdMap.set(ele.__config__.formId + "-table-" + element.__config__.formId,
              element.__config__.defaultValue);
          });
        }
        else if (ele.__config__.componentName && ele.__config__.componentName == 'avue-tabs') {
          let childrenObj = ele.__config__.childrenObj || {};
          let _arr = this.getValByTabs(childrenObj);
          _arr.map(item => {
            valueForFormIdMap.set(item.formId, item.defaultValue);
          });
        }
        else {
          valueForFormIdMap.set(ele.__config__.formId, this.formData[ele.__vModel__]);
        }
      });
      this.formConfig.fields.forEach((ele, index) => {
        if (ele.__config__.componentName == "table") {
          ele.__config__.children.forEach((element, childrenIndex) => {
            let defaultValue = 0;
            if (element.computationalConfiguration && element.computationalConfiguration.length > 0) {
              let formulaStr = "";
              element.computationalConfiguration.forEach((item) => {
                if (item.type == "taxRate") {
                  //税率
                  if (element.taxRate >= 0) {
                    formulaStr += element.taxRate * 0.01;
                  }
                }
                else {
                  let eleValue = valueForFormIdMap.get(item.formId) || 0;
                  formulaStr += item.formId == 0 ? item.name : eleValue;
                }
              });
              defaultValue = eval(formulaStr) * 100;
              defaultValue = this.getNumberFixed2(defaultValue) / 100;
              //大写
              if (element.isCapitalized) {
                this.formConfig.fields[index].__config__.children[childrenIndex].__config__
                  .capitalizedValue = this.getCapitalizedMethod(defaultValue);
              }
              this.formConfig.fields[index].__config__.children[childrenIndex].__config__
                .defaultValue = defaultValue;
              this.formData[element.__vModel__] = defaultValue;
            }
          });
        }
        else if (ele.__config__.componentName && ele.__config__.componentName == 'avue-tabs') {
          let childrenObj = ele.__config__.childrenObj || {};
          //avue-tabs
          this.calcDefaultValueByTabs(ele.__config__.childrenObj, valueForFormIdMap);
        }
        else {
          let defaultValue = 0;
          if (ele.computationalConfiguration && ele.computationalConfiguration.length > 0) {
            let formulaStr = "";
            ele.computationalConfiguration.forEach((item) => {
              if (item.type == "taxRate") {
                //税率
                if (ele.taxRate >= 0) {
                  formulaStr += ele.taxRate * 0.01;
                }
              }
              else {
                let eleValue = valueForFormIdMap.get(item.formId) || 0;
                formulaStr += item.formId == 0 ? item.name : eleValue;
              }
            });
            defaultValue = eval(formulaStr) * 100;
            defaultValue = this.getNumberFixed2(defaultValue) / 100;
            //大写
            if (ele.isCapitalized) {
              this.formConfig.fields[index].__config__.capitalizedValue = this.getCapitalizedMethod(
                defaultValue);
            }
            this.formConfig.fields[index].__config__.defaultValue = defaultValue;
            this.formData[ele.__vModel__] = defaultValue;
          }
        }
      });
    },
    getValByTabs(childrenObj) {
      let _arr = [];
      if (!childrenObj || !(childrenObj instanceof Object)) return [];
      for (let key in childrenObj) {
        let children = childrenObj[key];
        children.map(item => {
          if (item.__config__.componentName && item.__config__.componentName == 'avue-tabs') {
            let cObj = item.__config__.childrenObj || {};
            _arr.push(...this.getValByTabs(item.__config__.childrenObj));
          }
          else {
            let _obj = {};
            _obj.formId = item.__config__.formId;
            _obj.defaultValue = this.formData[item.__vModel__];
            _arr.push(_obj);
          }
        });
      }
      return (() => {
        return _arr;
      })()
    },
    calcDefaultValueByTabs(childrenObj, valueForFormIdMap) {
      if (!childrenObj || !(childrenObj instanceof Object)) return;
      for (let key in childrenObj) {
        let children = childrenObj[key];
        children.map(item => {
          if (item.__config__.componentName && item.__config__.componentName == 'avue-tabs') {
            let cObj = item.__config__.childrenObj || {};
            this.calcDefaultValueByTabs(cObj, valueForFormIdMap);
          }
          else {
            let defaultValue = 0;
            if (item.computationalConfiguration && item.computationalConfiguration.length > 0) {
              let formulaStr = "";
              item.computationalConfiguration.forEach((c) => {
                if (c.type == "taxRate") {
                  //税率
                  if (item.taxRate >= 0) {
                    formulaStr += item.taxRate * 0.01;
                  }
                }
                else {
                  let eleValue = valueForFormIdMap.get(c.formId) || 0;
                  formulaStr += c.formId == 0 ? c.name : eleValue;
                }
              });
              defaultValue = eval(formulaStr) * 100;
              defaultValue = this.getNumberFixed2(defaultValue) / 100;
              item.__config__.defaultValue = defaultValue;
              this.formData[item.__vModel__] = defaultValue;
            }
          }
        });
      }
    },
    async triggerEventHandler(eventData) {
      if (eventData.length > 0) {
        eventData.forEach(ele => {
          let functionName = 'getField' + ele.componentFormId + 'Options';
          if (typeof this[functionName] == "function") {
            this[functionName]();
          }
        })
      }
    },
    triggerEventFormIdHandler(formId) {
      if (this.formFieldsMap.get(formId).__config__.triggerEvents && this.formFieldsMap.get(formId).__config__
        .triggerEvents.length > 0) {
        this.formFieldsMap.get(formId).__config__.triggerEvents.forEach(triggerEventItem => {
          if (this.formFieldsMap.get(formId).__config__.triggerEventData && this.formFieldsMap.get(formId)
            .__config__.triggerEventData[triggerEventItem] && this.formFieldsMap.get(formId).__config__
            .triggerEventData[triggerEventItem].length > 0) {
            this.triggerEventHandler(this.formFieldsMap.get(formId).__config__.triggerEventData[
              triggerEventItem]);
          }
        });
      }
      return true;
    },
    //清空联想弹层、多选弹层的值
    clearBombLayerFormData(filed) {
      this.formData[filed] = '';
      this.formData[filed + '_showValue'] = '';
    },
    // 流程参数赋值
    processParameterAssignment() {
      // 流程中的流程参数赋值 优先级最高，最后赋值
      setTimeout(() => {
        if (this.isEdit != 2 && this.parameter && this.parameter[this.mainTableName]) {
          this.showForm = false;
          for (let [key, value] of Object.entries(this.parameter[this.mainTableName])) {
            this.setFormDataValue(key, value);
          }
          this.showForm = true;
        }
      }, 0);
    },
    setFormDataValue(field, val) {
      if (Array.isArray(this.formData[field])) {
        if (val.includes(',')) {
          this.formData[field] = val.split(',');
        }
        else {
          this.formData[field] = [val];
        }
      }
      else {
        this.formData[field] = val;
      }
      //处理联想弹层，多选弹层
      if (this.formData[field + '_showValue'] != undefined) {
        this.formData[field + '_showValue'] = val;
      }
    },
    setOutputsValue(nodeType, formId, res, outputKey) {
      let nodeTypeChecked = false;
      if (nodeType == 'created') {
        nodeTypeChecked = this.operationVal == 'add';
      }
      else if (nodeType == 'edit') {
        nodeTypeChecked = this.operationVal == 'edit';
      }
      else if (nodeType == 'mounted') {
        nodeTypeChecked = this.operationVal == 'add' || this.operationVal == 'edit';
      }
      if (nodeTypeChecked && this.disabled != true && res && res.data && res.data.data && this.formFieldsMap
        .has(formId) && this.formFieldsMap.get(formId).__vModel__ && this.formData.hasOwnProperty(this
          .formFieldsMap.get(formId).__vModel__)) {
        this.setFormDataValue(this.formFieldsMap.get(formId).__vModel__, res.data.data[outputKey]);
        // 联想弹层 多选弹层 特殊处理
        if (this.formFieldsMap.get(formId).__config__ && this.formFieldsMap.get(formId).__config__.avueType &&
          this.needShowValueTags.includes(this.formFieldsMap.get(formId).__config__.avueType)) {
          this.formData[this.formFieldsMap.get(formId).__vModel__ + '_showValue'] = res.data.data[outputKey];
        }
        this.triggerEventFormIdHandler(formId);
      }
    },
    //子表单权限
    getAuthorityTableChildrenList(bindTable, children) {
      let column = [];
      if (bindTable && this.formEnCodeList && this.formEnCodeList[bindTable]) {
        let formSubEnCodeList = this.formEnCodeList[bindTable];
        if (children && children.length > 0) {
          column = children.map(ele2 => {
            if (formSubEnCodeList.includes(ele2.prop)) {
              ele2.hide = false;
            }
            else {
              ele2.hide = true;
            }
            if (ele2.hide == false) {
              //工作流中系统表单必填权限
              if (this.formSubTableNotRequiredList && this.formSubTableNotRequiredList[bindTable] !=
                undefined) {
                if (this.formSubTableNotRequiredList[bindTable].includes(ele2.prop)) {
                  ele2.required = false;
                }
                else {
                  ele2.required = true;
                }
              }
              ele2.rules = [];
              if (ele2.required) {
                ele2.rules = ele2.ruleList;
              }
              // disabled 属性
              if (this.formSubTableDisabledList && this.formSubTableDisabledList[bindTable] !=
                undefined) {
                if (this.formSubTableDisabledList[bindTable].includes(ele2.prop)) {
                  ele2.disabled = true;
                }
                else {
                  ele2.disabled = false;
                }
              }
              if (this.disabled) { //查看
                ele2.disabled = true;
              }
            }
            else {
              ele2.rules = []
              if (ele2.required) {
                ele2.ruleList.forEach(el => {
                  el.message += ',' + this.$t('noFormAuth')
                })
                ele2.rules = ele2.ruleList;
              }
            }
            return ele2;
          });
        }
        return column;
      }
      else {
        return children;
      }
    },
    async insertCreatedEvent() {
      
    },
    async insertMountedEvent() {
      
    },
    async insertEditEvent() {
      
    },
    async insertSubmitEvent() {
      
    },
    getFormConfig() {
       return fieldsConfig();
    },
    getFormFieldsMap() {
       return formFieldsMap();
    },
    async getHideComponentsMap() {
      let mapList = new Map();
      let hideComponentList = this.getHideComponents();
      if (typeof this.initHideComponentList == 'function') {
        mapList = await this.initHideComponentList(hideComponentList);
        this.$store.commit("SET_HIDE_COMPONENT_LIST", mapList);
      }
      return mapList;
    },
    getHideComponentsMapItem(key) {
      if (this.hideComponentsMap.size > 0) {
        return this.hideComponentsMap.has(key) ? this.hideComponentsMap.get(key) : "";
      }
      else {
        return ""
      }
    },
    getHideComponents() {
       return getHideComponents();
    },
  }
}

</script>
<style>
.el-table__empty-block {
  width: 100% !important;
}

.avue-form__row {
  padding: 0 !important;
}

#editorphone {
  width: 375px;
  margin: 0 auto;
  border: 1px solid #E4E7ED;
  padding: 0 7.5px;
  background: #f5f6fa;
  height: 700px;
  overflow-y: auto;
  overflow-x: hidden;
  border-radius: 5px;
}

#editorphone .el-col {
  border-bottom: 1px solid #F2F2F2;
  background: #fff;
  margin-bottom: 0;
  padding: 0 15px 6px !important;
  width: 100%;
}

#editorphone .el-form-item__label {
  line-height: 20px
}

#editorphone .el-input-group .el-input__inner {
  background: #f5f6fa
}

#editorphone .el-input__inner {
  border: 0
}

#editorphone .el-input-group__append,
#editorphone .el-input-group__prepend {
  border: 0;
  background: #edeef2;
  color: #666;
}

#editorphone .el-input-group .el-input__prefix {
  left: 44px
}

#editorphone .el-input-group .el-input__suffix {
  right: 44px
}

#editorphone .el-form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-flow: wrap;
}

#editorphone .el-form-item__label {
  float: none;
  min-width: 85px;
  width: auto !important;
  text-align: left;
  flex: auto;
}

#editorphone .tinymce .el-form-item__label {
  min-width: 100%;
}

#editorphone .el-form-item__content {
  margin-left: 0px !important;
  flex: auto;
  width: calc(100% - 95px);
}

#editorphone .avueFormNoLable .el-form-item__label,
#editorphone .avueFormNoLable .avue-crud__pagination {
  display: none;
}

#editorphone .avueFormNoLable .el-collapse-item__wrap,
#editorphone .avueFormNoLable .el-collapse {
  border-bottom: 0
}

#editorphone .avueFormNoLable .el-col {
  border-bottom: 0;
  padding-bottom: 0
}

#editorphone .el-form-item__content .el-button:first-child {
  margin-left: 90px;
}

</style>
